package com.mce.nebula.service;

import com.mce.nebula.entity.Team;
import com.mce.nebula.entity.TeamRole;
import com.mce.nebula.entity.TeamRolePermission;
import com.mce.nebula.entity.TeamUser;
import com.mce.nebula.entity.User;
import com.mce.nebula.repository.TeamRepository;
import com.mce.nebula.repository.TeamRoleRepository;
import com.mce.nebula.repository.TeamRolePermissionRepository;
import com.mce.nebula.repository.TeamUserRepository;
import com.mce.nebula.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * 权限管理服务
 * 对应Python的InitPerms功能
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PermissionService {
    
    private final TeamRepository teamRepository;
    private final TeamUserRepository teamUserRepository;
    private final TeamRoleRepository teamRoleRepository;
    private final TeamRolePermissionRepository teamRolePermissionRepository;
    private final UserRepository userRepository;
    
    /**
     * 初始化权限设置
     */
    @Transactional
    public void initPermissions(String enterpriseId, String tenantId) {
        List<Team> teams;
        
        if (tenantId != null && enterpriseId != null) {
            // 根据租户ID和企业ID查找团队
            teams = teamRepository.findByTenantIdAndEnterpriseId(tenantId, enterpriseId);
        } else if (tenantId != null) {
            // 根据租户ID查找团队
            teams = teamRepository.findByTenantId(tenantId);
        } else if (enterpriseId != null) {
            // 根据企业ID查找团队
            teams = teamRepository.findByEnterpriseId(enterpriseId);
        } else {
            // 查找所有团队
            teams = teamRepository.findAll();
        }
        
        if (teams.isEmpty()) {
            log.info("未发现团队, 初始化结束");
            return;
        }
        
        for (Team team : teams) {
            initTeamPermissions(team);
        }
        
        log.info("权限初始化完成，处理了 {} 个团队", teams.size());
    }
    
    /**
     * 初始化团队权限
     */
    private void initTeamPermissions(Team team) {
        try {
            // 初始化默认角色
            initDefaultRoles(team);
            
            // 获取团队成员
            List<TeamUser> teamUsers = teamUserRepository.findByTenantId(team.getTenantId());
            
            if (!teamUsers.isEmpty()) {
                // 为团队成员分配角色
                assignRolesToUsers(team, teamUsers);
            }
            
            log.info("团队 {} 权限初始化完成", team.getTenantName());
        } catch (Exception e) {
            log.error("初始化团队 {} 权限失败", team.getTenantName(), e);
            throw new RuntimeException("权限初始化失败: " + e.getMessage());
        }
    }
    
    /**
     * 初始化默认角色
     */
    private void initDefaultRoles(Team team) {
        try {
            // 创建管理员角色
            TeamRole adminRole = createOrGetRole(team, "管理员", "admin", "团队管理员，拥有所有权限");
            
            // 创建开发者角色
            TeamRole developerRole = createOrGetRole(team, "开发者", "developer", "团队开发者，拥有开发和部署权限");
            
            // 为角色分配权限
            assignPermissionsToRole(adminRole, getAdminPermissions());
            assignPermissionsToRole(developerRole, getDeveloperPermissions());
            
            log.debug("为团队 {} 初始化默认角色完成", team.getTenantName());
        } catch (Exception e) {
            log.error("初始化团队 {} 默认角色失败", team.getTenantName(), e);
            throw new RuntimeException("初始化默认角色失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建或获取角色
     */
    private TeamRole createOrGetRole(Team team, String roleName, String roleAlias, String description) {
        Optional<TeamRole> existingRole = teamRoleRepository.findByTenantIdAndRoleName(team.getTenantId(), roleName);
        
        if (existingRole.isPresent()) {
            return existingRole.get();
        }
        
        TeamRole role = new TeamRole();
        role.setRoleId(UUID.randomUUID().toString().replace("-", ""));
        role.setTenantId(team.getTenantId());
        role.setRoleName(roleName);
        role.setRoleAlias(roleAlias);
        role.setDescription(description);
        role.setIsActive(true);
        role.setEnterpriseId(team.getEnterpriseId());
        
        return teamRoleRepository.save(role);
    }
    
    /**
     * 为角色分配权限
     */
    private void assignPermissionsToRole(TeamRole role, List<String> permissionCodes) {
        // 先删除现有权限
        teamRolePermissionRepository.deleteByRoleId(role.getRoleId());
        
        // 添加新权限
        for (String permissionCode : permissionCodes) {
            TeamRolePermission permission = new TeamRolePermission();
            permission.setRoleId(role.getRoleId());
            permission.setPermissionCode(permissionCode);
            permission.setPermissionName(getPermissionName(permissionCode));
            permission.setPermissionDesc(getPermissionDesc(permissionCode));
            permission.setIsActive(true);
            permission.setEnterpriseId(role.getEnterpriseId());
            
            teamRolePermissionRepository.save(permission);
        }
    }
    
    /**
     * 获取管理员权限列表
     */
    private List<String> getAdminPermissions() {
        return List.of(
            "team:read", "team:write", "team:delete",
            "app:read", "app:write", "app:delete", "app:deploy",
            "user:read", "user:write", "user:delete",
            "config:read", "config:write",
            "log:read", "monitor:read"
        );
    }
    
    /**
     * 获取开发者权限列表
     */
    private List<String> getDeveloperPermissions() {
        return List.of(
            "team:read",
            "app:read", "app:write", "app:deploy",
            "log:read", "monitor:read"
        );
    }
    
    /**
     * 获取权限名称
     */
    private String getPermissionName(String permissionCode) {
        switch (permissionCode) {
            case "team:read": return "查看团队";
            case "team:write": return "编辑团队";
            case "team:delete": return "删除团队";
            case "app:read": return "查看应用";
            case "app:write": return "编辑应用";
            case "app:delete": return "删除应用";
            case "app:deploy": return "部署应用";
            case "user:read": return "查看用户";
            case "user:write": return "编辑用户";
            case "user:delete": return "删除用户";
            case "config:read": return "查看配置";
            case "config:write": return "编辑配置";
            case "log:read": return "查看日志";
            case "monitor:read": return "查看监控";
            default: return permissionCode;
        }
    }
    
    /**
     * 获取权限描述
     */
    private String getPermissionDesc(String permissionCode) {
        switch (permissionCode) {
            case "team:read": return "可以查看团队信息";
            case "team:write": return "可以编辑团队信息";
            case "team:delete": return "可以删除团队";
            case "app:read": return "可以查看应用信息";
            case "app:write": return "可以编辑应用信息";
            case "app:delete": return "可以删除应用";
            case "app:deploy": return "可以部署应用";
            case "user:read": return "可以查看用户信息";
            case "user:write": return "可以编辑用户信息";
            case "user:delete": return "可以删除用户";
            case "config:read": return "可以查看配置信息";
            case "config:write": return "可以编辑配置信息";
            case "log:read": return "可以查看日志信息";
            case "monitor:read": return "可以查看监控信息";
            default: return "系统权限";
        }
    }
    
    /**
     * 为用户分配角色
     */
    private void assignRolesToUsers(Team team, List<TeamUser> teamUsers) {
        for (TeamUser teamUser : teamUsers) {
            try {
                User user = userRepository.findById(teamUser.getUserId().longValue()).orElse(null);
                if (user == null) {
                    log.warn("用户 {} 不存在，跳过角色分配", teamUser.getUserId());
                    continue;
                }
                
                // 根据用户身份分配角色
                if (teamUser.getUserId().equals(team.getCreater())) {
                    // 团队创建者分配管理员角色
                    assignAdminRole(team, user);
                } else {
                    // 其他用户分配开发者角色
                    assignDeveloperRole(team, user);
                }
                
                log.debug("为用户 {} 分配角色完成", user.getNickName());
            } catch (Exception e) {
                log.error("为用户 {} 分配角色失败", teamUser.getUserId(), e);
            }
        }
    }
    
    /**
     * 分配管理员角色
     */
    private void assignAdminRole(Team team, User user) {
        try {
            Optional<TeamRole> adminRole = teamRoleRepository.findByTenantIdAndRoleName(team.getTenantId(), "管理员");
            if (adminRole.isPresent()) {
                // 这里应该更新用户的角色信息
                // 简化处理，实际应该调用用户角色服务
                log.debug("为用户 {} 分配管理员角色 {}", user.getNickName(), adminRole.get().getRoleName());
            } else {
                log.warn("未找到团队 {} 的管理员角色", team.getTenantName());
            }
        } catch (Exception e) {
            log.error("为用户 {} 分配管理员角色失败", user.getNickName(), e);
        }
    }
    
    /**
     * 分配开发者角色
     */
    private void assignDeveloperRole(Team team, User user) {
        try {
            Optional<TeamRole> developerRole = teamRoleRepository.findByTenantIdAndRoleName(team.getTenantId(), "开发者");
            if (developerRole.isPresent()) {
                // 这里应该更新用户的角色信息
                // 简化处理，实际应该调用用户角色服务
                log.debug("为用户 {} 分配开发者角色 {}", user.getNickName(), developerRole.get().getRoleName());
            } else {
                log.warn("未找到团队 {} 的开发者角色", team.getTenantName());
            }
        } catch (Exception e) {
            log.error("为用户 {} 分配开发者角色失败", user.getNickName(), e);
        }
    }
}
